package com.pm.controller;

import com.pm.entity.User;
import com.pm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户管理控制器
 */
@RestController
@RequestMapping("/api/users")
@CrossOrigin(origins = "*")
public class UserController {
    
    @Autowired
    private UserService userService;
    
    /**
     * 获取所有用户
     */
    @GetMapping
    public ResponseEntity<List<User>> getAllUsers() {
        List<User> users = userService.getAllUsers();
        return ResponseEntity.ok(users);
    }
    
    /**
     * 根据ID获取用户
     */
    @GetMapping("/{id}")
    public ResponseEntity<?> getUserById(@PathVariable String id) {
        try {
            User user = userService.findById(id);
            if (user == null) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "用户不存在");
                return ResponseEntity.badRequest().body(error);
            }
            return ResponseEntity.ok(user);
        } catch (Exception e) {
            Map<String, String> error = new HashMap<>();
            error.put("error", "获取用户信息失败");
            return ResponseEntity.badRequest().body(error);
        }
    }
    
    /**
     * 更新用户信息
     */
    @PutMapping("/{id}")
    public ResponseEntity<?> updateUser(@PathVariable String id, @RequestBody User user, Authentication authentication) {
        try {
            // 检查权限：只能更新自己的信息或管理员权限
            String currentUsername = authentication.getName();
            User currentUser = userService.findByUsername(currentUsername);
            User targetUser = userService.findById(id);
            
            if (targetUser == null) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "用户不存在");
                return ResponseEntity.badRequest().body(error);
            }
            
            if (!currentUser.getId().equals(id)) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "无权限修改其他用户信息");
                return ResponseEntity.badRequest().body(error);
            }
            
            user.setId(id);
            User updatedUser = userService.updateUser(user);
            
            Map<String, Object> response = new HashMap<>();
            response.put("user", updatedUser);
            response.put("message", "用户信息更新成功");
            
            return ResponseEntity.ok(response);
            
        } catch (RuntimeException e) {
            Map<String, String> error = new HashMap<>();
            error.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }
    
    /**
     * 删除用户
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteUser(@PathVariable String id, Authentication authentication) {
        try {
            // 检查权限：不能删除自己
            String currentUsername = authentication.getName();
            User currentUser = userService.findByUsername(currentUsername);
            
            if (currentUser.getId().equals(id)) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "不能删除自己的账户");
                return ResponseEntity.badRequest().body(error);
            }
            
            boolean deleted = userService.deleteUser(id);
            if (!deleted) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "删除用户失败");
                return ResponseEntity.badRequest().body(error);
            }
            
            Map<String, String> response = new HashMap<>();
            response.put("message", "用户删除成功");
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            Map<String, String> error = new HashMap<>();
            error.put("error", "删除用户失败");
            return ResponseEntity.badRequest().body(error);
        }
    }
    
    /**
     * 修改密码
     */
    @PostMapping("/{id}/change-password")
    public ResponseEntity<?> changePassword(@PathVariable String id, @RequestBody ChangePasswordRequest request, Authentication authentication) {
        try {
            // 检查权限：只能修改自己的密码
            String currentUsername = authentication.getName();
            User currentUser = userService.findByUsername(currentUsername);
            
            if (!currentUser.getId().equals(id)) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "无权限修改其他用户密码");
                return ResponseEntity.badRequest().body(error);
            }
            
            boolean changed = userService.changePassword(id, request.getOldPassword(), request.getNewPassword());
            if (!changed) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "原密码错误");
                return ResponseEntity.badRequest().body(error);
            }
            
            Map<String, String> response = new HashMap<>();
            response.put("message", "密码修改成功");
            
            return ResponseEntity.ok(response);
            
        } catch (RuntimeException e) {
            Map<String, String> error = new HashMap<>();
            error.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }
    
    /**
     * 修改密码请求DTO
     */
    public static class ChangePasswordRequest {
        private String oldPassword;
        private String newPassword;
        
        // Getters and Setters
        public String getOldPassword() {
            return oldPassword;
        }
        
        public void setOldPassword(String oldPassword) {
            this.oldPassword = oldPassword;
        }
        
        public String getNewPassword() {
            return newPassword;
        }
        
        public void setNewPassword(String newPassword) {
            this.newPassword = newPassword;
        }
    }
}